#pragma once
#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "nocopy.hpp"
#include "log.hpp"
#include "comm.hpp"

const static uint16_t defaultport = 8888;
const static int defaultfd = -1;
const static int defaultsize = 1024;

class udpserver : public nocopy
{
public:
    udpserver(const std::string &ip, uint16_t port = defaultport)
        : _ip(ip), _port(port), _sockfd(defaultfd)
    {
    }
    void init()
    {
        // 1创建socket，就是创建文件细节
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            lg.LogMessage(Fatal, "socket errr,%d : %s\n", errno, strerror(errno));
            exit(socket_err);
        }
        lg.LogMessage(Info, "socket success,sockfd:%d\n", _sockfd);
        // 2 绑定 制定网络信息
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = inet_addr(_ip.c_str());

        // 结构体填完并没有设置到内核中
        int n = ::bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n != 0)
        {
            lg.LogMessage(Fatal, "bind error,%d :%s\n", errno, strerror(errno));
            exit(bind_err);
        }
    }
    void start()
    {
        char buffer[defaultsize];
        for (;;)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&peer,&len);
            if(n >0)
            {
                buffer[n] =0;
                std::cout<<"client say#" << buffer <<std::endl;
                sendto(_sockfd,buffer,strlen(buffer),0,(struct sockaddr *)&peer,len);
            }
        }
    }
    ~udpserver() {}

private:
    std::string _ip;
    uint16_t _port;
    int _sockfd;
};
